package ynu.edu.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.dto.FoodCategoryDTO;
import ynu.edu.entity.Food;
import ynu.edu.entity.FoodCategory;
import ynu.edu.repository.FoodCategoryRepository;
import ynu.edu.repository.FoodRepository;
import ynu.edu.repository.MerchantRepository;
import ynu.edu.service.FoodCategoryService;

import jakarta.persistence.EntityNotFoundException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 食品分类服务实现类
 */
@Service
@RequiredArgsConstructor
public class FoodCategoryServiceImpl implements FoodCategoryService {
    
    private final FoodCategoryRepository foodCategoryRepository;
    private final MerchantRepository merchantRepository;
    private final FoodRepository foodRepository;
    
    /**
     * 根据商家ID获取食品分类列表
     *
     * @param businessId 商家ID
     * @return 食品分类列表
     */
    @Override
    public List<FoodCategoryDTO> getCategoriesByBusinessId(Integer businessId) {
        // 验证商家是否存在
        if (!merchantRepository.existsById(businessId)) {
            throw new EntityNotFoundException("未找到ID为" + businessId + "的商家");
        }
        
        List<FoodCategory> categories = foodCategoryRepository.findByBusinessIdOrderBySortAsc(businessId);
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据ID获取食品分类
     *
     * @param categoryId 分类ID
     * @return 食品分类信息
     */
    @Override
    public FoodCategoryDTO getCategoryById(Integer categoryId) {
        FoodCategory category = foodCategoryRepository.findById(categoryId)
                .orElseThrow(() -> new EntityNotFoundException("未找到ID为" + categoryId + "的食品分类"));
        return convertToDTO(category);
    }
    
    /**
     * 添加食品分类
     *
     * @param categoryDTO 食品分类信息
     * @return 添加后的食品分类信息
     */
    @Override
    @Transactional
    public FoodCategoryDTO addCategory(FoodCategoryDTO categoryDTO) {
        // 验证商家是否存在
        if (!merchantRepository.existsById(categoryDTO.getBusinessId())) {
            throw new EntityNotFoundException("未找到ID为" + categoryDTO.getBusinessId() + "的商家");
        }
        
        // 检查分类名称是否重复
        FoodCategory existingCategory = foodCategoryRepository
                .findByBusinessIdAndName(categoryDTO.getBusinessId(), categoryDTO.getName());
        if (existingCategory != null) {
            throw new IllegalArgumentException("该商家下已存在同名分类");
        }
        
        FoodCategory category = new FoodCategory();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        
        FoodCategory savedCategory = foodCategoryRepository.save(category);
        return convertToDTO(savedCategory);
    }
    
    /**
     * 更新食品分类
     *
     * @param categoryDTO 食品分类信息
     * @return 更新后的食品分类信息
     */
    @Override
    @Transactional
    public FoodCategoryDTO updateCategory(FoodCategoryDTO categoryDTO) {
        FoodCategory category = foodCategoryRepository.findById(categoryDTO.getId())
                .orElseThrow(() -> new EntityNotFoundException("未找到ID为" + categoryDTO.getId() + "的食品分类"));
        
        // 验证商家是否存在
        if (!merchantRepository.existsById(categoryDTO.getBusinessId())) {
            throw new EntityNotFoundException("未找到ID为" + categoryDTO.getBusinessId() + "的商家");
        }
        
        // 检查分类名称是否重复（排除自身）
        FoodCategory existingCategory = foodCategoryRepository
                .findByBusinessIdAndName(categoryDTO.getBusinessId(), categoryDTO.getName());
        if (existingCategory != null && !existingCategory.getId().equals(categoryDTO.getId())) {
            throw new IllegalArgumentException("该商家下已存在同名分类");
        }
        
        BeanUtils.copyProperties(categoryDTO, category);
        category.setUpdateTime(LocalDateTime.now());
        
        FoodCategory updatedCategory = foodCategoryRepository.save(category);
        return convertToDTO(updatedCategory);
    }
    
    /**
     * 删除食品分类
     *
     * @param categoryId 分类ID
     */
    @Override
    @Transactional
    public void deleteCategory(Integer categoryId) {
        if (!foodCategoryRepository.existsById(categoryId)) {
            throw new EntityNotFoundException("未找到ID为" + categoryId + "的食品分类");
        }
        
        // 检查是否有食品使用此分类
        List<Food> foods = foodRepository.findByBusinessIdAndCategoryId(null, categoryId);
        if (!foods.isEmpty()) {
            throw new IllegalStateException("无法删除分类，该分类下仍有" + foods.size() + "个食品");
        }
        
        foodCategoryRepository.deleteById(categoryId);
    }
    
    /**
     * 将实体转换为DTO
     *
     * @param category 食品分类实体
     * @return 食品分类DTO
     */
    private FoodCategoryDTO convertToDTO(FoodCategory category) {
        FoodCategoryDTO categoryDTO = new FoodCategoryDTO();
        BeanUtils.copyProperties(category, categoryDTO);
        return categoryDTO;
    }
} 